package fussbudget.gui.components;

import java.awt.Component;
import java.awt.Point;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTable;

public class BasicPopupMenu extends JPopupMenu {
	protected ArrayList<HasPopupMenu>	parents	= new ArrayList<HasPopupMenu>();
	protected int rowNumber = -1;

	public BasicPopupMenu(HasPopupMenu parent) {
		super();
		parent.addMouseListener(new PopupListener());
		parents.add(parent);
	}

	public BasicPopupMenu(ArrayList<HasPopupMenu> parents) {
		super();
		for (HasPopupMenu currParent : parents) {
			currParent.addMouseListener(new PopupListener());
			currParent.setPopup(this);
		}
		this.parents = parents;
	}

	public JMenu addMenu(String label) {
		JMenu newMenu = new JMenu(label);
		add(newMenu);
		return newMenu;
	}

	public JMenuItem addMenuItem(String label, ActionListener action) {
		JMenuItem newMenuItem = new JMenuItem(label);
		newMenuItem.addActionListener(action);
		add(newMenuItem);
		return newMenuItem;
	}

	public JMenuItem addMenuItem(String label, JMenu menuParent, ActionListener action) {
		JMenuItem newMenuItem = new JMenuItem(label);
		newMenuItem.addActionListener(action);
		menuParent.add(newMenuItem);
		return newMenuItem;
	}

	public class PopupListener extends MouseAdapter {
		public void mousePressed(MouseEvent e) {
			maybeShowPopup(e);
		}

		public void mouseReleased(MouseEvent e) {
			maybeShowPopup(e);

		}

		public void maybeShowPopup(MouseEvent e) {
			Point p = e.getPoint();
			Component c = e.getComponent();
			int X = e.getX();
			int Y = e.getY();
			
			if (c instanceof JTable) {
				rowNumber = ((JTable) c).rowAtPoint(p);
				if (rowNumber != -1) {
					((JTable)c).getSelectionModel().setSelectionInterval(rowNumber, rowNumber);
				}
			}
			
			if (e.isPopupTrigger() || e.getButton() == MouseEvent.BUTTON3) {
				show(e.getComponent(), e.getX(), e.getY());
			}
		}
	}
	
	public int getRow(){
		return rowNumber;
	}
}
